package main

// 分公司订单恢复

import (
	"github.com/gogap/logs"
	"yundian/internel/app/logic"
	"yundian/internel/pkg/dbs"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

func main() {
	//dingo.InitViper("./configs/adm.yaml")
	//dingo.InitViper("./configs/zmtest-adm.yaml")
	dingo.InitViper("./configs/zhongman.yaml")
	dbs.NewMysqlComponent().Step()

	var tradeNoPlaceList []struct {
		T  string
		Id int
	}

	tradeNoPlaceListSql := `SELECT min(trade_no)t,place_id id FROM orders WHERE trade_no>='ZM20210820' AND trade_no IN (
    SELECT trade_no FROM (SELECT our.trade_no,min(user_id)user_id FROM orders_user_relevancy our WHERE our.user_id>218 AND 
	trade_no IN (SELECT trade_no FROM dividends_log WHERE user_id=219 AND end_date>='2021-08-01'
	) GROUP BY our.trade_no) a WHERE user_id>219) GROUP BY place_id`
	if db := global.Orm.Debug().Raw(tradeNoPlaceListSql).Find(&tradeNoPlaceList); db.Error != nil {
		logs.Error(db.Error)
		return
	}

	for _, item := range tradeNoPlaceList {
		var tradeNoList []string
		tradeNoSql := `SELECT trade_no FROM orders WHERE place_id=? AND trade_no>=?`
		if db := global.Orm.Debug().Raw(tradeNoSql, item.Id, item.T).Find(&tradeNoList); db.Error != nil {
			logs.Error(db.Error)
			return
		}

		if db := global.Orm.Debug().Exec("DELETE FROM orders_user_relevancy WHERE trade_no IN (?)", tradeNoList); db.Error != nil {
			logs.Error(db.Error)
			return
		}

		var orderListUse []logic.OrderListUseType
		orderSql := `SELECT o.*,p.branch_user_id,DATE_FORMAT(FROM_UNIXTIME(o.end_at), '%Y-%m-%d')end_date,DATE_FORMAT(
		FROM_UNIXTIME(o.end_at), '%Y-%m')end_month FROM orders o LEFT JOIN places p ON o.place_id=p.id WHERE o.trade_no in (?) 
		ORDER BY o.id`
		if db := global.Orm.Raw(orderSql, tradeNoList).Find(&orderListUse); db.Error != nil {
			logs.Error(db.Error)
			return
		}
		logic.NewTaskLogic().OrderRelevanceSyncDataExec(orderListUse, 300)
	}
}
